import logger from '@common/logger';
import dayjs from 'dayjs';
import { MARKET_ACTIVITY_OFFER_TYPE, MARKET_ACTIVITY_OFFER_ITEM_TYPE } from '@constants/market';
import { DELIVERY_TYPE } from '@constants/shop';
/**
 * 获取商品可用的优惠券
 * @param {String|Number} prodId 商品id
 * @param {Array} couponList 优惠券列表
 */
const getProdCanUserCoupon = (prodId, couponList) => {
    logger.debugger('Review => 优惠券列表', couponList);
    let result = [];
    couponList.forEach(item => {
        if (item.isAll) {
            logger.debugger('Review => 全部可用');
            result.push(item);
        } else if (item.include.indexOf(prodId) > -1 || item.exclude.indexOf(prodId) == -1) {
            result.push(item);
        }
    });
    return result;
};

/**
 * 去重合并两个优惠券数组
 * @param {Array} oneList 优惠券数组
 * @param {Array} twoList 优惠券数组
 */
const compareCouponList = (oneList, twoList) => {
    const allList = [...oneList, ...twoList];
    const targetIdList = Array.from(new Set(allList.map(item => item.id)));
    console.log(targetIdList);
    return targetIdList.map(item => {
        return allList.filter(temp => temp.id == item)[0];
    });
};

/**
 * 订单数据添可用优惠券数据
 * @param {Array} reviewList 数据
 * @param {Array} couponList 优惠券列表
 */
export const reviewListAddCoupon = (reviewList, couponList) => {
    logger.debugger('Review => 添加优惠券', reviewList, couponList);
    const result = [];
    for (let i = 0; i < reviewList.length; i++) {
        const list = reviewList[i].list;
        let _couponList = [];
        list.forEach(item => {
            _couponList = compareCouponList(_couponList, getProdCanUserCoupon(item.id, couponList));
        });
        result.push({
            ...reviewList[i],
            couponList: _couponList,
        });
    }
    return result;
};

/**
 * 转换为试算数据
 * @param {Array} reviewList 列表
 */
export const reviewListToMarketList = (reviewList) => {
    logger.debugger('Review => 转换试算数据', reviewList);
    return reviewList.map((item, index) => {
        return {
            owner_id: index,
            coupon_sns: item.useCoupon,
            trial_items: item.list.map((temp, idx) => {
                return {
                    scene_detail_id: `detail-${idx}`,
                    scene_detail_cnt: temp.quantity,
                    item_id: temp.prod_id,
                    item_spec_id: temp.sku_id,
                    item_price: temp.price,
                };
            }),
        };
    });
};

/**
 * 处理优惠项信息
 * @param {Array} offerItems 门店优惠项
 */
const dealDiscountItemsInfo = (offerItems) => {
    let prodsList = [];
    let activityDiscount = 0;
    let couponDiscount = 0;
    offerItems.forEach(item => {
        if (item.offer_item_type == MARKET_ACTIVITY_OFFER_ITEM_TYPE.activity && item.offer_type == MARKET_ACTIVITY_OFFER_TYPE.quotaCut) {
            activityDiscount += item.off;
        }
        if (item.offer_item_type == MARKET_ACTIVITY_OFFER_ITEM_TYPE.coupon) {
            couponDiscount += item.off;
        }
        prodsList = [...prodsList, ...item.off_trial_items];
    });
    return {
        prodsList,
        activityDiscount,
        couponDiscount,
    };
};

/**
 * 单品添加优惠金额
 * @param {Object} prodInfo 商品信息
 * @param {Array} discountList 优惠商品列表
 */
const prodAddDiscount = (prodInfo, discountList) => {
    const _discountItem = discountList.filter(item => item.item_id == prodInfo.prod_id && item.item_spec_id == prodInfo.sku_id)[0];
    logger.warn('Review => 单项', _discountItem);
    if (_discountItem && _discountItem.off > 0) {
        return {
            ...prodInfo,
            discountPrice: prodInfo.price - (_discountItem.off / prodInfo.quantity),
            totalOffer: _discountItem.off,
        };
    }
    return prodInfo;
};

/**
 * 结算列表添加优惠信息
 * @param {Array} reviewList 待结算列表
 * @param {Object} discountInfo 优惠信息
 */
export const reviewListAddDiscountInfo = (reviewList, discountInfo) => {
    const { owners } = discountInfo;
    return reviewList.map((item, index) => {
        const offInfo = owners.filter(t => t.owner_id == index)[0];
        const { prodsList, activityDiscount, couponDiscount } = dealDiscountItemsInfo(offInfo.offer_items);
        logger.warn('Reivew => 优惠商品列表', prodsList, activityDiscount);
        return {
            ...item,
            list: item.list.map(temp => prodAddDiscount(temp, prodsList)),
            discountInfo: {
                activityDiscount,
                couponDiscount,
            },
        };
    });
};

/**
 * 修改备注
 * @param {Array} list 数据
 * @param {Number} id 门店ID
 * @param {String} remark 备注信息
 */
export const changeReviewItemRemark = (list, id, remark) => {
    return list.map(item => {
        return {
            ...item,
            remark: item.id == id ? remark : item.remark,
        };
    });
};

/**
 * 修改使用的优惠券
 * @param {Array} list 数据
 * @param {Number} id 门店ID
 * @param {Array} useCoupon 优惠券sn数组
 */
export const changeReviewItemUseCoupon = (list, id, useCoupon) => {
    return list.map(item => {
        return {
            ...item,
            useCoupon: item.id == id ? useCoupon : item.useCoupon,
        };
    });
};

/**
 * 计算订单价格
 * @param {Array} reviewList 确认订单数据列表
 * @param {Number} deliveryType 配送方式
 */
export const calcReviewOrderPrice = (reviewList, deliveryType) => {
    let totalPrice = 0;
    let totalDiscountPrice = 0;
    const list = reviewList.map(item => {
        const result = calcReviewOrderItemPrice(item, deliveryType);
        totalDiscountPrice += result.totalDiscountPrice;
        totalPrice += result.totalPrice;
        return result;
    });
    return {
        list,
        totalPrice,
        totalDiscountPrice,
    };
};

/**
 * 计算快递费
 * @param {Object} item 商品信息
 * @param {Object} info 快递费信息
 * @returns
 */
const calcExpressPrice = (item, info) => {
    let price = 0;
    if (!info) return price;
    const { additional, first } = info;
    const weight = item.weight * item.quantity / 1000;
    logger.info('Review => 物品：', item);
    logger.debugger('Review => 当前货物重量为：', weight);
    if (weight > 1) {
        price = (first - 0) + Math.ceil(weight - 1) * (additional - 0);
    } else {
        price = first - 0;
    }
    return price;
};

/**
 * 计算整个包裹的快递费
 * @param {Array} list 包裹商品列表
 * @param {Object} info 快递费计算规则
 */
const calcPackageExpressPrice = (list, info) => {
    // 计算整个包裹的重量
    let price = 0;
    logger.debugger('Review => 计算快递费', info);
    if (!info) return price;
    const { additional, first } = info;
    let allWeight = 0;
    list.forEach(item => {
        allWeight += item.weight * item.quantity / 1000;
    });
    if (allWeight > 1) {
        price = (first - 0) + Math.ceil(allWeight - 1) * (additional - 0);
    } else {
        price = first - 0;
    }
    return price;
};

/**
 * 计算同城配送费
 * @param {Object} item 商品信息
 * @param {Object} info 快递费信息
 * @returns
 */
const calcCityExpressPrice = (item, infoList) => {
    if (infoList.length === 0) return 0;
    const itemPrice = item.price * item.quantity;
    let priceResult = [];
    infoList.forEach(temp => {
        if (itemPrice >= (temp.start_fee - 0)) {
            priceResult.push(temp.express_fee - 0);
        }
    });
    return priceResult.length > 0 ? Math.min(...priceResult) : 0;
};

const calcPackageCityExpressPrice = (list, infoList) => {
    // 计算整个包裹的价格
    let totalPrice = 0;
    // if (!info) return price;
    list.forEach(item => {
        totalPrice += item.price * item.quantity;
    });
    return calcCityExpressPrice({ price: totalPrice, quantity: 1 }, infoList);
};

/**
 * 计算单个订单的总价&优惠信息
 * @param {Object} reviewOrderItem 单个订单信息
 * @param {Number} deliveryType 配送方式
 */
export const calcReviewOrderItemPrice = (reviewOrderItem, deliveryType) => {
    const { list, warehouseInfo = {}, discountInfo } = reviewOrderItem;
    let totalPrice = 0;
    let totalDiscountPrice = 0;
    let deliveryPrice = 0;
    const { city_regions = [], ordinary_express_config = {} } = warehouseInfo;
    const { activityDiscount = 0, couponDiscount = 0 } = discountInfo;
    list.forEach(item => {
        const { price, totalOffer = 0, quantity } = item;
        totalPrice += price * quantity;
        logger.error('Review => 优惠项', totalOffer);
        totalDiscountPrice += totalOffer;
    });
    totalDiscountPrice += activityDiscount;
    totalDiscountPrice += couponDiscount;
    switch(deliveryType) {
    case DELIVERY_TYPE.EXPRESS:
        deliveryPrice = calcPackageExpressPrice(list, ordinary_express_config);
        break;
    case DELIVERY_TYPE.CITY_EXPRESS:
        deliveryPrice = calcPackageCityExpressPrice(list, city_regions);
        break;
    case DELIVERY_TYPE.SELF_PICK_UP:
        deliveryPrice = 0;
        break;
    }
    logger.debugger('Review => 计算的快递为', deliveryPrice);
    logger.error('Review => 计算结果', totalPrice + deliveryPrice - totalDiscountPrice, totalDiscountPrice);
    return {
        ...reviewOrderItem,
        deliveryPrice,
        totalPrice: totalPrice + deliveryPrice - totalDiscountPrice,
        totalDiscountPrice,
    };
};

export const dealCombinedOrderParam = (reviewList, deliveryType, off = 0, bookDays) => {
    return reviewList.map(item => {
        const { warehouseInfo } = item;
        return {
            store_id: item.id,
            details: item.list.map(temp => {
                return {
                    prod_id: temp.prod_id,
                    sku_id: temp.sku_id,
                    quantity: temp.quantity,
                    memo: '',
                    origin: temp.price,
                };
            }),
            warehouse_id: warehouseInfo ? warehouseInfo.id : 0,
            deliver_type: deliveryType,
            deliver_fee: item.deliveryPrice,
            booking_days: bookDays || 0,
            discount: item.totalDiscountPrice + off,
            trans: item.totalPrice - off,
            remark: item.remark,
        };
    });
};

export const getDayText = (len) => {
    const time = dayjs().add(len, 'day');
    return `${time.format('MM.DD')}`;
};

export const getReviewProdList = (reviewList) => {
    let result = [];
    for (let i = 0; i < reviewList.length; i++) {
        result = [...result, ...reviewList[i].list];
    }
    return result;
};
